import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  // 路由输入错误，或没有路由，显示首页
  {
    path: '*',
    name: 'All',
    redirect: '/Home',
    component: () => import('@/views/Home')
  },
  // 首页路由
  {
    path: '/Home',
    name: 'Home',
    component: () => import('@/views/Home')
  },
  // 登录路由
  {
    path: '/Login',
    name: 'Login',
    component: () => import('@/views/Login')
  },
  // 个人中心，修改密码路由
  {
    path: '/MyInfo',
    name: 'MyInfo',
    component: () => import('@/views/MyInfo')
  },
  // 容器路由
  {
    path: '/Container',
    name: 'Container',
    component: () => import('@/views/Container')
  },
  // 容器详情路由
  {
    path: '/Container/ConContent/:id',
    name: 'ConContent',
    component: () => import('@/views/container/ConContent')
  },
  // 镜像路由
  {
    path: '/Image',
    name: 'Image',
    component: () => import('@/views/Image')
  },
  // 镜像详情路由
  {
    path: '/Image/ImageContent/:id',
    name: 'ImageContent',
    component: () => import('@/views/image/ImageContent')
  },
  // 镜像拉取路由
  {
    path: '/Image/ImagePull',
    name: 'ImagePull',
    component: () => import('@/views/image/ImagePull')
  },
  // 集群路由
  {
    path: '/Colony',
    name: 'Colony',
    component: () => import('@/views/Colony')
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

// 全局路由守卫，检测用户是否登录
router.beforeEach((to, from, next) => {
  const user = localStorage.getItem('user')
  if (to.name === 'Login') {
    next()
  } else {
    if (!user) {
      // console.log(location)
      if (location.search) {
        // 获取数据
        var str = location.search
        // 去掉？
        str = str.replace('?', '')
        // 处理成数组
        var arr = str.split('&')
        // 处理成对象
        var userItem = {}
        arr.map(item => {
          var itemarr = item.split('=')
          userItem[itemarr[0]] = itemarr[1]
          return itemarr
        })
        // 存localStorage
        localStorage.setItem('baseURL', userItem.baseURL)
        localStorage.setItem('token', userItem.token)
        localStorage.setItem('user', JSON.stringify(userItem))
        localStorage.setItem('userList', JSON.stringify([userItem]))
        // 跳转路由
        setTimeout(() => {
          next({ path: '/Home' })
        }, 500)
      } else {
        // localStorage.setItem('baseURL', 'http://123.206.78.77:8081') // 开发环境
        localStorage.setItem('baseURL', location.origin) // 上线环境
        next({ path: '/Login' })
      }
    } else {
      next()
    }
  }
})

export default router
